package dao

import (
	"user/model"
	"user/utils"
)

func GetUserByTelephone(telephone string) *model.User {
	sql := "SELECT `id`,`name`,`telephone`,`password` FROM `users` WHERE `telephone`=? LIMIT 1"
	stmt, err := DB.Prepare(sql)
	defer stmt.Close()
	utils.CheckError(err)

	row, err := stmt.Query(telephone)
	utils.CheckError(err)
	user := model.User{}
	if row.Next() {
		row.Scan(&user.ID, &user.UserName, &user.Telephone, &user.Password)
	}
	return &user
}

func GetUserInfoById(id int) *model.User {
	sql := "SELECT `id`,`name`,`telephone` FROM `users` WHERE `id`=? LIMIT 1"
	stmt, err := DB.Prepare(sql)
	defer stmt.Close()
	utils.CheckError(err)
	row := stmt.QueryRow(id)
	var user model.User
	row.Scan(&user.ID, &user.UserName, &user.Telephone)
	return &user
}

func AddUser(user model.User) int64 {
	sql := "INSERT INTO `users`(`name`,`telephone`,`password`,`created_at`,`updated_at`) VALUES(?,?,?,now(),now())"
	stmt, err := DB.Prepare(sql)
	defer stmt.Close()
	utils.CheckError(err)
	result, err := stmt.Exec(user.UserName, user.Telephone, user.Password)
	utils.CheckError(err)
	id, err := result.LastInsertId()
	utils.CheckError(err)
	return id
}
